//
//  MessageListViewController.m
//  IhuayuanClient
//
//  Created by 黄思清 on 2017/7/5.
//  Copyright © 2017年 com.ihuayuan. All rights reserved.
//

#import "MessageListViewController.h"
#import "CellForMessage.h"
#import "CellForMessageRight.h"
#import "MessageListModel.h"
#import "UITableViewCell+HYBMasonryAutoCellHeight.h"

#import "MessagePostViewController.h"


@interface MessageListViewController ()<UITableViewDelegate,UITableViewDataSource,CellForMessageDelegate,CellForMessageRightDelegate,PassValueDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableDictionary *heightDict;
@property (nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) NSMutableArray *RequestArr;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSMutableArray *firstArr;
//@property (nonatomic ,weak) TGRefreshOC *refreshCtl;//高级用法时这行可以去掉

@end

@implementation MessageListViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = @"留言管理";
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"留言管理";
    UIButton *rightbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightbutton.frame= CGRectMake(0, 10, 44, 44);
    rightbutton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
    [rightbutton addTarget:self action:@selector(rightOnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarbutton = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    [rightbutton setImage:[[UIImage imageNamed:@"publish"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    self.navigationItem.rightBarButtonItem = leftBarbutton;
    [self initUI];
}

- (void)initUI
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    self.tableView.delegate   = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[CellForMessage class] forCellReuseIdentifier:NSStringFromClass([CellForMessage class])];

    [self.tableView registerClass:[CellForMessageRight class] forCellReuseIdentifier:NSStringFromClass([CellForMessageRight class])];


    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self requestDataLoadNew:YES];
    }];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self doRefreshSenior];
    }  ];
    [self.tableView.mj_header beginRefreshing];
}

-(void)doRefreshSenior
{
    self.page = 1;
    [self requestDataLoadNew:YES];
}

-(NSMutableArray *)RequestArr
{
    if (!_RequestArr)
    {
        _RequestArr = [NSMutableArray array];
    }
    return _RequestArr;
}

#pragma mark - Lazy Load
- (NSMutableArray *)dataArray{
    if (!_dataArray)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableDictionary *)heightDict{
    if (!_heightDict)
    {
        _heightDict = [NSMutableDictionary new];
    }
    return _heightDict;
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count == 0) {
        self.tableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nodata"]];
    }else
    {
        self.tableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
    }
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YHWorkGroup *model  = self.dataArray[indexPath.row];
    if(model.delPass==NO){
        CellForMessage *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CellForMessage class])];
        if (!cell) {
            cell = [[CellForMessage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([CellForMessage class])];
        }
        cell.indexPath = indexPath;
        cell.model     = model;
        cell.delegate  = self;
        return cell;
    }else
    {
        CellForMessageRight *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CellForMessageRight class])];
        if (!cell) {
            cell = [[CellForMessageRight alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([CellForMessageRight class])];
        }
        cell.indexPath = indexPath;
        cell.model = model;
        cell.delegate  = self;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FLT_MIN;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row < self.dataArray.count)
    {
        CGFloat height = 0.0;
        YHWorkGroup *model  = self.dataArray[indexPath.row];
        //取缓存高度
        NSDictionary *dict =  self.heightDict[model.dynamicId];
        if (dict) {
            if (model.isOpening) {
                height = [dict[@"open"] floatValue];
            }else
            {
                height = [dict[@"normal"] floatValue];
            }
            if (height)
            {
                return height;
            }
        }
        if(model.delPass==NO){
            height = [CellForMessage hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
                CellForMessage *cell = (CellForMessage *)sourceCell;
                cell.model = model;
            }];
        }else{
            height = [CellForMessageRight hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
                CellForMessageRight *cell = (CellForMessageRight *)sourceCell;
                cell.model = model;
            }];
        }
        //缓存高度
//        if (model.dynamicId) {
//            NSMutableDictionary *aDict = [NSMutableDictionary new];
//            if (model.isOpening) {
//                [aDict setObject:@(height) forKey:@"open"];
//            }else{
//                [aDict setObject:@(height) forKey:@"normal"];
//            }
//            [self.heightDict setObject:aDict forKey:model.dynamicId];
//        }
        return height;
    }else{
        return 44.0f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 网络请求
- (void)requestDataLoadNew:(BOOL)loadNew
{
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCoursemsg&a=index" parmDic:@{@"caid":self.caid,@"page":[NSString stringWithFormat:@"%ld",self.page]} requestType:RequestGET Success:^(id data)
    {
        self.firstArr= [MessageListModel modelConfigure:data];
        if (self.page == 1) {
            [self.RequestArr removeAllObjects];
            [self.dataArray removeAllObjects];
        }
        if (self.firstArr.count==0) {
            self.page--;
        }

        [self.RequestArr addObjectsFromArray:self.firstArr];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];

        NSInteger totalCount = self.RequestArr.count;
        NSUInteger lastDynamicID = 0;

        if (!loadNew && self.dataArray.count) {
            YHWorkGroup *model = self.dataArray.lastObject;
            lastDynamicID = [model.dynamicId integerValue];
        }

        for (NSInteger i=0; i<totalCount; i++) {
            YHWorkGroup *model = [YHWorkGroup new];
            model.dynamicId = [NSString stringWithFormat:@"%lu", lastDynamicID + i+1];
            [self randomModel:model totalCount:i];
            [self.dataArray addObject:model];
        }

        [self.tableView reloadData];
        if (self.firstArr.count == 0||self.firstArr.count<10)
        {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }

    } error:^(NSError *error) {

    }];
}



#pragma mark - 模拟产生数据源
- (void)randomModel:(YHWorkGroup *)model totalCount:(NSInteger)totalCount
{
    [self creatOriModel:model totalCount:totalCount];
}

- (void)creatOriModel:(YHWorkGroup *)model totalCount:(NSInteger)totalCount
{
    MessageListModel *myModel = self.firstArr[totalCount];
    model.msgContent  = myModel.contents;
    model.bottomLeft  = myModel.addtimedesc;
    
    if([myModel.type isEqualToString:@"1"]){
        model.delPass     = YES;
    }else{        
        model.delPass     = NO;
    }

    //原图
    NSMutableArray *oriPName = [@[] mutableCopy];
    //小图
    NSMutableArray *thumbPName = [@[] mutableCopy];

    for (NSString *picUrl in myModel.thumbs)
    {
        NSString *longPicUrl = [NSString stringWithFormat:@"%@%@",KUrl,picUrl];
        [thumbPName addObject:longPicUrl];
    }

    for (NSString *picUrl in myModel.thumbs)
    {
        NSString *longPicUrl = [NSString stringWithFormat:@"%@%@",KUrl,picUrl];

        NSString *bigPicUrl = [longPicUrl stringByReplacingOccurrencesOfString:@"/thumb" withString:@""];

        [oriPName addObject:bigPicUrl];
    }


    NSMutableArray *thumbPArr = [NSMutableArray new];

    for (NSString *pName in thumbPName)
    {
        [thumbPArr addObject:[NSURL URLWithString:pName]];
    }

    NSMutableArray *oriPArr = [NSMutableArray new];
    for (NSString *pName in oriPName)
    {
        [oriPArr addObject:[NSURL URLWithString:pName]];
    }

    model.originalPicUrls = oriPArr;
    model.thumbnailPicUrls = thumbPArr;
}


#pragma mark - CellForMessageDelegate
- (void)onMoreInCell:(CellForMessage *)cell{
    if (cell.indexPath.row < [self.dataArray count]) {
        YHWorkGroup *model = self.dataArray[cell.indexPath.row];
        model.isOpening = !model.isOpening;
        [self.tableView reloadRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)onDeleteInCell:(CellForMessage *)cell
{
    NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
    MessageListModel *model = self.RequestArr[indexpath.row];

    [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCoursemsg&a=deleteMsg" parmDic:@{@"aid":model.aid} requestType:RequestPOST Success:^(id data)
    {
        [self.RequestArr removeObjectAtIndex:indexpath.row];
        [self.dataArray removeObjectAtIndex:indexpath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:(UITableViewRowAnimationRight)];

    } error:^(NSError *error)
    {

    }];
}

#pragma mark - private
- (void)_deleteDynAtIndexPath:(NSIndexPath *)indexPath dynamicId:(NSString *)dynamicId
{
    
}

-(void)rightOnClick
{
    MessagePostViewController * messagePostVc = [[MessagePostViewController alloc]init];
    messagePostVc.Delegate = self;
    messagePostVc.caid = self.caid;
    [self.navigationController pushViewController:messagePostVc animated:YES];
}


/**
 代理执行过了之后的刷新界面
 */
-(void)reloadDataList
{
//    [self.dataArray removeAllObjects];
//    [self.RequestArr removeAllObjects];
//    [self.tableView reloadData];
//    [self requestDataLoadNew:YES];
    
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCoursemsg&a=index" parmDic:@{@"caid":self.caid} requestType:RequestGET Success:^(id data)
    {
        NSArray *modelArr = [MessageListModel modelConfigure:data];
        MessageListModel *myModel = [modelArr firstObject];
        [self.RequestArr addObject:myModel];

        YHWorkGroup *model = [YHWorkGroup new];
        model.msgContent  = myModel.contents;
        model.bottomLeft  = myModel.addtimedesc;

        if([myModel.type isEqualToString:@"1"]){
            model.delPass     = YES;
        }else{
            model.delPass     = NO;
        }
        //原图
        NSMutableArray *oriPName = [@[] mutableCopy];
        //小图
        NSMutableArray *thumbPName = [@[] mutableCopy];

        for (NSString *picUrl in myModel.thumbs)
        {
            NSString *longPicUrl = [NSString stringWithFormat:@"%@%@",KUrl,picUrl];
            [thumbPName addObject:longPicUrl];
        }

        for (NSString *picUrl in myModel.thumbs)
        {
            NSString *longPicUrl = [NSString stringWithFormat:@"%@%@",KUrl,picUrl];

            NSString *bigPicUrl = [longPicUrl stringByReplacingOccurrencesOfString:@"/thumb" withString:@""];

            [oriPName addObject:bigPicUrl];
        }

        NSMutableArray *thumbPArr = [NSMutableArray new];
        for (NSString *pName in thumbPName)
        {
            [thumbPArr addObject:[NSURL URLWithString:pName]];
        }

        NSMutableArray *oriPArr = [NSMutableArray new];
        for (NSString *pName in oriPName)
        {
            [oriPArr addObject:[NSURL URLWithString:pName]];
        }
        
        model.originalPicUrls = oriPArr;
        model.thumbnailPicUrls = thumbPArr;

        [self.dataArray insertObject:model atIndex:0];
        
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexpath] withRowAnimation:(UITableViewRowAnimationFade)];

    } error:^(NSError *error) {

    }];
}

//-(void)addNewData:(MessageListModel *)model
//{
//    [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCoursemsg&a=index" parmDic:@{@"caid":self.caid,@"page":[NSString stringWithFormat:@"%ld",self.page]} requestType:RequestGET Success:^(id data)
//     {
//         self.RequestArr = [MessageListModel modelConfigure:data];
//
//         NSInteger totalCount = self.RequestArr.count;
//
//         NSUInteger lastDynamicID = 0;
//
//         if (!loadNew && self.dataArray.count) {
//             YHWorkGroup *model = self.dataArray.lastObject;
//             lastDynamicID = [model.dynamicId integerValue];
//         }
//
//         for (NSInteger i=0; i<totalCount; i++) {
//             YHWorkGroup *model = [YHWorkGroup new];
//             model.dynamicId = [NSString stringWithFormat:@"%lu", lastDynamicID + i+1];
//             [self randomModel:model totalCount:i];
//             [self.dataArray addObject:model];
//         }
//         
//         [self.tableView reloadData];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
